package com.handler;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Hashtable;

import utl.mofen.utils.GsonUtil;

import com.google.gson.JsonObject;
import com.netty.handler.JSonStreamNettyHandler;

public class FileRecvHandler extends JSonStreamNettyHandler{
	private static Hashtable<String, FileOutputStream> foCache = new Hashtable<String, FileOutputStream>();
	
	JsonObject jsonObject = null;
	
	public void doAction() throws Exception {
		
		jsonObject = this.jsonStream.getJSonObject();
		
		if (!jsonObject.has("fileInfo"))
		{
			jsonStream.clear();
			throw new Exception("缺少文件头信息!");
		}
		
		JsonObject fileInfo = jsonObject.get("fileInfo").getAsJsonObject();
		if (!fileInfo.has("id"))
		{
			jsonStream.clear();
			throw new Exception("头信息缺少id!");
		}
		
		String id = fileInfo.get("id").getAsString();
		System.out.println(GsonUtil.json2String(fileInfo));

		FileOutputStream fo = this.foCache.get(id);
		if (fo==null)
		{
			File file = new File("C:\\cache\\" + fileInfo.get("file").getAsString());
			if (file.exists())
			{
				if (!file.delete())
				{
					throw new Exception("服务端文件被占用，不能进行覆盖!");
				}
			}
 
			fo = new FileOutputStream(file);
			foCache.put(id, fo);
		}
		fo.write(jsonStream.getStream());		
		
		//判断是否完成
		if (fileInfo.has("end"))
		{
			if (fileInfo.get("end").getAsBoolean())
			{
				fo.close();
				foCache.remove(id);
			}
		}
	}
}
